package com.xyh.reward_kotlin.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.updatePadding
import com.xyh.reward_kotlin.R
import com.xyh.reward_kotlin.response.RewardResultDto
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class HistoryDetailActivity : AppCompatActivity() {

    private var scoresContainer: LinearLayout? = null
    private var currentRankView: TextView? = null

    @SuppressLint("WrongViewCast", "SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_history_detail)
        Log.d("historyDetail", "onCreate: Activity启动")

        // 关闭系统默认 Insets 处理
        WindowCompat.setDecorFitsSystemWindows(window, false)
        window.statusBarColor = Color.TRANSPARENT
        val controller = WindowInsetsControllerCompat(window, window.decorView)
        controller.isAppearanceLightStatusBars = true

        val rootView = findViewById<ScrollView>(R.id.historyDetailRoot)
        ViewCompat.setOnApplyWindowInsetsListener(rootView) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            Log.d("historyDetail", "Insets: top=${systemBars.top}, bottom=${systemBars.bottom}")
            v.updatePadding(top = systemBars.top, bottom = systemBars.bottom)
            insets
        }

        val titleView = findViewById<TextView>(R.id.detailTitle)
        val timeView = findViewById<TextView>(R.id.detailTime)
        val contentView = findViewById<TextView>(R.id.detailContent)
        val baseDetailView = findViewById<TextView>(R.id.baseDetailContent)
        val extraDetailView = findViewById<TextView>(R.id.extraDetailContent)
        val specialDetailView = findViewById<TextView>(R.id.specialDetailContent)
        scoresContainer = findViewById(R.id.scoresContainer)
        currentRankView = findViewById(R.id.currentRankView)

        // 获取传递的数据
        val reward = intent.getParcelableExtra<RewardResultDto>("rewardItem")
        Log.d("historyDetail", "接收到rewardItem: $reward")
        if (reward == null) {
            Log.e("historyDetail", "未获取rewardItem，Activity结束")
            finish()
            return
        }

        // 填充内容
        val title = "总奖励：${reward.totalReward}"
        Log.d("historyDetail", "设置标题: $title")
        val fullContent = """
            奖励总金额：${reward.totalReward}
            总分：${reward.total}（核心：${reward.coreTotal}，综合：${reward.generalTotal}）
            当前排名：${reward.currentRank}
        """.trimIndent()
        val baseDetail = """
            基础奖励（${reward.base}）
            达标条件：${reward.baseDesc}
        """.trimIndent()
        val extraDetail = """
            额外奖励（${reward.extra}）
            达标条件：${reward.extraDesc}
        """.trimIndent()
        val specialDetail = """
            特殊奖励（${reward.special}）
            达标条件：${reward.specialDesc}
        """.trimIndent()

        titleView.text = title
        timeView.text = formatTimestamp(reward.timestamp)
        contentView.text = fullContent
        baseDetailView.text = baseDetail
        extraDetailView.text = extraDetail
        specialDetailView.text = specialDetail

        // 动态展示科目成绩
        reward.studentDto?.scores?.forEach { (subject, score) ->
            Log.d("historyDetail", "科目成绩: $subject=$score")
            val tv = TextView(this)
            tv.text = "$subject : $score"
            tv.textSize = 16f
            tv.setPadding(0, 4, 0, 4)
            scoresContainer?.addView(tv)
        }

        currentRankView?.text = "当前排名: ${reward.currentRank}"
        Log.d("historyDetail", "页面填充完毕")
    }

    private fun formatTimestamp(timestamp: Long): String {
        val date = Date(timestamp)
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        return sdf.format(date)
    }
}